<?php

namespace App\V3\Api\Controllers;

/* use App\Http\Controllers\Controller; */
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use App\Helper\Utils\TimeUtil;
use App\V3\Api\Services\DeliverySlipService;
use App\V3\Api\Models\DeliverySlipModel;
use App\Http\Controllers\Api\BaseController;
use App\V3\Api\Models\DeliveryGoodsModel;
use App\V3\Api\Services\DispatchListService;
use App\V3\Api\Models\AdminAddendumModel;
use OSS\OssClient;
class DeliverySlipController extends BaseController
{
    protected $ossClient;
    public function __construct(Request $request){
        parent::__construct($request);
        $this->ossClient=new OssClient(
            config('app.aliyun_oss_key'),
            config('app.aliyun_oss_secret'),
            config('app.aliyun_oss_endpoint')
            );
    }
    /**
     * 添加送货单
     */
    public function add(Request $request){

        $admininfo   = AdminAddendumModel::select('is_vip','empty_bill_amount')->where(['main_id'=>$this->getMainUserId()])->first()->toArray();

        if(!empty($admininfo) && in_array($admininfo['is_vip'],[1,2])){

         /*    $total_amount = DispatchListService::countReceiptsTotal(['main_id'=>$this->getMainUserId()]);

            if($admininfo['empty_bill_amount'] >0 && $total_amount >= $admininfo['empty_bill_amount']){

                return $this->fail('','您创建的送货单，已达到设置数量！');
            } */

        }else{

            return $this->fail('','您还不是VIP会员，还不能创建空白单据！');
        }

        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'total_cost'        =>'numeric|min:0',//总费用

        ],[
            'total_cost.numeric'   => '本单费用只能为数字',
            'total_cost.min'       => '本单费用最小只能为0',

        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        if(!empty($customer_signature_files = $request->file('customer_signature'))){

            if($customer_signature_files->isValid()){

                $img_path = $customer_signature_files->store('qm/imgs/'.date('Y').'-'.date('m').'-'.date('d'));

                $imgRes   = SELF::addOssUploadImg($this->getMainUserId(),$this->ossClient, $customer_signature_files, $img_path);
                    if($imgRes['code'] === 0){
                        $data['customer_signature'] = $imgRes['data'];
                    }else{
                        return response()->json($imgRes);
                    }
            }else{
                return response()->json(['code' => 1,'msg' => '提货人签字，添加失败！','data' => '']);
            }
        }
        //开启事务
       DB::beginTransaction();
        try{
            //送货单
            $dData = $data;
            $dData['created_at']   = time();
            $dData['user_id']      = $this->getUserId();
            $dData['main_id']      = $this->getMainUserId();

            if(empty($dData['delivery_no'])){

                $dData['delivery_no']  = 'F'. $this->getMainUserId().TimeUtil::getMillisecond();//送货单号

            }else{

                $condition['delivery_no'] = $dData['delivery_no'];
                $condition['user_id']  = $this->getUserId();
                $condition['main_id']  = $this->getMainUserId();

                $info = DeliverySlipService::getDeliverySlipInfo($condition);

                if(!empty($info)){

                    return $this->fail('','送货单编号,已存在！');
                }
            }
            unset($dData['goods_info']);
            $delivery_id           = DeliverySlipService::add($dData);
            //$data['goods_info']='[{"name":"苹果","type_name":"红","product_unit":"件","price":"5.6","num":"10","number_parcels":"5","serial_number":11},{"name":"水梨","type_name":"黄","product_unit":"件","price":"3.6","num":"8","number_parcels":"4","serial_number":22}]';
            //商品详细添加
            if(isset($data['goods_info']) && !empty($data['goods_info'])){

                $goodsInfo = json_decode($data['goods_info'],true);
                if(is_array($goodsInfo)){
                    foreach ($goodsInfo as &$value){

                        $value['created_at'] = time();
                        $value['delivery_id'] = $delivery_id;
                        $value['user_id']     = $this->getUserId();
                        $value['main_id']     = $this->getMainUserId();
                    }

                    DeliveryGoodsModel::insert($goodsInfo);
                }
            }

            DB::commit();//提交事务
            return $this->success();
        }catch (\Exception $e){
            DB::rollBack();//事务回滚
            //异常响应
            return $this->fail($e->getMessage(),'添加送货单');
        }

    }

    /**
     * 删除送货单信息
     * @param ids (删除多个逗号分隔)
     */
    public function delete(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'ids'       =>'required',//送货单id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg'  => $info,
                'data' => '',
            ]);
        }

        $id_data = [];
        $id_arr  = explode(',',$data['ids']);

        $condition['user_id'] = $this->getUserId();
        $condition['main_id'] = $this->getMainUserId();

        $list = DeliverySlipModel::select('id','customer_signature')->where($condition)->whereIn('id',$id_arr)->get()->toArray();

        if(!empty($list)){

            foreach ($list as $k=>$v){

                $id_data[]=$v['id'];
                $delOssRes = SELF::delOssFilePath($v['customer_signature'], $this->ossClient, $this->getMainUserId());

                if(!empty($delOssRes)) return $this->fail('',$delOssRes);
            }
            $bool = DeliverySlipModel::where($condition)->whereIn('id',$id_data)->delete();

            if($bool){

                DeliveryGoodsModel::where($condition)->whereIn('delivery_id',$id_data)->delete();

                return $this->success();

            }else{
                return $this->fail('','删除失败');
            }

        }
        return $this->fail('','送货单，不存在！');
    }


    /**
     * 删除商品
     * @param Request $request
     */
    public function delGoods(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'goods_ids'         => 'required',//商品id
            'delivery_id'      => 'required',//送货单id
        ],[
            'delivery_id.required' => '送货单主键id`缺失`',
            'goods_ids.required' => '商品主键id`缺失`'

        ]);

        $id_arr  = explode(',',$data['goods_ids']);

        $condition['user_id'] = $this->getUserId();
        $condition['main_id'] = $this->getMainUserId();
        $condition['delivery_id'] = $data['delivery_id'];
        DeliveryGoodsModel::where($condition)->whereIn('id',$id_arr)->delete();
        return $this->success();
    }

    /**
     * 修改送货单
     *
     */
    public function update(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'delivery_id'       =>'required|integer',//送货单id
            'total_cost'        =>'numeric|min:0',//总费用
            'total_number'      =>'numeric|min:0',//商品总件数
        ],[
            'delivery_id.required'   => '送货单主键id缺失',
            'delivery_id.integer'   => '送货单主键id为正整数',
            'total_cost.numeric'   => '本单费用只能为数字',
            'total_cost.min'       => '本单费用最小只能为0',
            'total_number.numeric' => '商品件数只能为数字',
            'total_number.min'     => '商品件数最小只能为0',
            'phone.regex'          => '收货人手机号,格式错误!',

        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $info = DeliverySlipService::getDeliverySlipInfo(['id'=> $data['delivery_id']]);

        if(empty($info)){

            return $this->fail('','送货单号,不存在！');
        }

        if(!empty($customer_signature_files = $request->file('customer_signature'))){

            if($customer_signature_files->isValid()){

                $img_path = $customer_signature_files->store('qm/imgs/'.date('Y').'-'.date('m').'-'.date('d'));


                $imgRes  = SELF::addOssUploadImg($this->getMainUserId(),$this->ossClient, $customer_signature_files, $img_path);

                if($imgRes['code'] === 0){
                    $data['customer_signature'] = $imgRes['data'];
                }else{
                    return response()->json($imgRes);
                }
            }else{
                return response()->json(['code' => 1,'msg' => '提货人签字，修改失败！','data' => '']);
            }

        }
        //开启事务
        DB::beginTransaction();
        try{
            //送货单
            $updData = $data;

            $condition['user_id'] = $this->getUserId();
            $condition['main_id'] = $this->getMainUserId();
            $condition['id']      = $updData['delivery_id'];
            //$updData['goods_info']='[{"goods_id":1,"name":"葡萄11","type_name":"紫11","product_unit":"件","price":"5.611","num":"1011","number_parcels":"5","serial_number":11},{"goods_id":2,"name":"水梨2222","type_name":"黄22","product_unit":"件","price":"3.6","num":"8","number_parcels":"4","serial_number":22},{"name":"水梨8888","type_name":"黄888","product_unit":"件","price":"3.6","num":"8","number_parcels":"4","serial_number":22}]';

            if(isset($updData['goods_info']) && !empty($updData['goods_info'])){

                $goodsInfo = json_decode($updData['goods_info'],true);
                if(is_array($goodsInfo)){
                    foreach ($goodsInfo as $value){//更新商品信息
                        //更新
                        if(isset($value['goods_id'])){

                            $dCondition['id'] = $value['goods_id'];

                            unset($value['goods_id']);

                            DeliveryGoodsModel::where($dCondition)->update($value);
                        }else{//添加

                            $value['created_at']  = time();
                            $value['user_id']     = $this->getUserId();
                            $value['main_id']     = $this->getMainUserId();
                            $value['delivery_id'] = $updData['delivery_id'];

                            DeliveryGoodsModel::insert($value);
                        }
                    }
                }
                unset($updData['goods_info']);
            }

            $updData['updated_at'] = time();
            unset($updData['delivery_id']);
            $bool = DeliverySlipService::update($condition,$updData);
            if($bool){
                if(!empty($customer_signature_files = $request->file('customer_signature'))){
                    //删除oss里的文件
                    $delOssRes = SELF::delOssFilePath($info['customer_signature'], $this->ossClient, $this->getMainUserId());
                    if(!empty($delOssRes)){

                        return $this->fail('',$delOssRes);
                    };
                }
            }
            DB::commit();//提交事务
            return $this->success();
        }catch (\Exception $e){
            DB::rollBack();//事务回滚
            //异常响应
            return $this->fail($e->getMessage(),'修改送货单');
        }

    }

    /**
     * 送货单信息
     * @param delivery_id
     */
    public function find(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'delivery_id'       =>'required|integer',//送货单id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg'  => $info,
                'data' => '',
            ]);
        }

        $condition['id'] = $data['delivery_id'];
     
        $info = DeliverySlipService::getDeliverySlipInfo($condition);
        $list = $info;
        if(!empty($info)){

            $list['goods_list']= DeliveryGoodsModel::where(['delivery_id'=>$info['id']])->get();

        }

        return $this->success($list);
    }

    /**
     * 送货单列表
     */
    public function DeliverySlipList(Request $request){

        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'page_size' =>'required|integer',//页面大小
            'current_page' =>'required|integer',//当前页
        ], [
            'page_size.required' => '参数`页面大小`丢失',
            'page_size.integer' => '参数`页面大小`仅能为数字',
            'current_page.required' => '参数`当前页码`丢失',
            'current_page.integer' => '参数`当前页码`仅能为数字',
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $id_arr01 = [];
        $id_arr02 = [];
        $delivery_id_arr = [];

        $keyword = empty($data['keyword'])?'':$data['keyword'];
       
        if($this->getMainUserId() != 0){
            if($this->getUserId() == $this->getMainUserId()) {
        
                $condition['main_id'] = $this->getMainUserId();
            }
            else {
                if($this->isShareBillhead()) {        
                    $condition['main_id'] = $this->getMainUserId();
                }else {
                    $condition['main_id'] = $this->getMainUserId();
                    $condition['user_id'] = $this->getUserId();
                }
            }
        }else{
            $condition['user_id'] = $this->getUserId();
        }
        
        if(!empty($keyword)){

            $goodsList = DeliveryGoodsModel::select('delivery_id')
            ->where($condition)
            ->where(function($query) use ($keyword) {
                $query->orWhere('name', 'like', '%'.$keyword.'%');
                $query->orWhere('type_name', 'like', '%'.$keyword.'%');
                $query->orWhere('serial_number', 'like', '%'.$keyword.'%');
            })
            ->orderBy('delivery_id','DESC')
            ->get()->toArray();

            if(!empty($goodsList)){

                foreach ($goodsList as $k=>$v){

                    $id_arr01[$k] = $v['delivery_id'];
                }
            }

            $list = DeliverySlipModel::select('id')->where($condition)
            ->where(function($query) use ($keyword) {
                $query->orWhere('delivery_no', 'like', '%'.$keyword.'%');
                $query->orWhere('consignee', 'like', '%'.$keyword.'%');
                $query->orWhere('consignee_phone', 'like', '%'.$keyword.'%');
                $query->orWhere('consignee_address', 'like', '%'.$keyword.'%');
            })->orderBy('id','desc')
            ->get()->toArray();

            if(!empty($list)){

                foreach ($list as $k=>$v){

                    $id_arr02[$k] = $v['id'];
                }
            }

            $delivery_id_arr = array_unique(array_merge($id_arr01,$id_arr02));

            if(empty($delivery_id_arr)){

                $delivery_id_arr[0] ="0";
            }
        }

        $list = DeliverySlipService::getList($condition,$delivery_id_arr,$data['page_size'],$data['current_page']);

        if(!empty($list['data'])){

            foreach ($list['data'] as &$value){

                $query = DeliveryGoodsModel::where('delivery_id',$value['id']);

                if(!empty($id_arr01)){

                    $query->where(function($query) use ($keyword) {
                        $query->orWhere('name', 'like', '%'.$keyword.'%');
                        $query->orWhere('type_name', 'like', '%'.$keyword.'%');
                        $query->orWhere('serial_number', 'like', '%'.$keyword.'%');
                    });
                }
                $value['goods_info'] =  $query->get();
            }
        }
        return $this->success($list);
    }

    /**
     * 图片上传到oss系统
     * @param unknown $client
     * @param unknown $file
     */
    static public function addOssUploadImg($mainId,$client,$file,$path){
        $res = handleUploadFileType($file);
        if(!empty($res)) return $res;
        $size = $file -> getSize();
         $result = saveFileSize(['main_id'=>$mainId], $size,$path);

         if($result['code'] == 1) return $result;
        try {

            $fullPath = '/uploads/'.$path;
            $ossPath  = ltrim($fullPath,'./');
            $path     = public_path().$fullPath;
            $client -> uploadFile(config('app.aliyun_oss_bucket'), $ossPath, $path);
            @unlink($path);
            $url = config('app.aliyun_oss_bucket_url').$fullPath;
            return ["code"=>0,"msg"=>"success","data"=>$url];

        } catch (\Exception $e) {

            return ["code"=>1,"msg"=>"OSS系统，上传图片失败！","data"=>""];
        }
    }


    /**
     * 删除oss里的文件
     * @param unknown $file
     * @param unknown $mainId
     */
    static public function delOssFilePath($file,$client,$mainId){
        if(empty($file)) return $file;
            DB::beginTransaction();
            try {
                $delPath = strstr($file, 'uploads/');
                $imgInfo=$client->getObjectMeta(config('app.aliyun_oss_bucket'), $delPath);
                AdminAddendumModel::where(['main_id'=>$mainId])
                ->decrement('file_total_size', $imgInfo['content-length']);
                $client -> deleteObject(config('app.aliyun_oss_bucket'), $delPath);
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack(); 
                return "";
            }
    }
}
